package com.bluesky.example.concurrent;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class RequestWorkThread extends Thread {

	int number;
	 Socket connection;

	public RequestWorkThread( Socket connection, int number) {
		this.connection = connection;
		this.number = number;

	}

	@Override
	public void run() {
		handleRequest(connection, number);
		System.out.println("handle" + number);

	}

	private void handleRequest(Socket socket, int number) {
		String radd = socket.getRemoteSocketAddress().toString();
		System.out.println("connected from " + radd);

		long servingTheadId = Thread.currentThread().getId();
		try {

			InputStreamReader isReader = new InputStreamReader(socket
					.getInputStream());
			BufferedReader bReader = new BufferedReader(isReader);

			OutputStreamWriter writer = new OutputStreamWriter(socket
					.getOutputStream());
			BufferedWriter bWriter = new BufferedWriter(writer);

			bWriter.write("Welcome, you are being served by thead "
					+ servingTheadId);

			bWriter.newLine();
			bWriter.write("you are the No." + number + "th guest");

			bWriter.newLine();

			bWriter.flush();

			while (true) {
				String request = bReader.readLine();

				System.out.println("client" + number + " said:" + request);

				bWriter.write("you said:" + request);
				bWriter.newLine();
				bWriter.flush();
				if (request.equalsIgnoreCase("quit")) {
					bWriter.write("bye!");
					bWriter.flush();
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
